/**
*
*/
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>自动生成表格页</el-breadcrumb-item>
    </el-breadcrumb>
    <NoPermission
      v-if="!authFilter(permissionObj, 'index')">
    </NoPermission>

    <div v-else>
      <!-- 搜索筛选 -->
      <el-form :inline="true" :model="formInline" class="mgt20">
        <el-form-item>
          <AutoCompleteCustom
            size="small"
            class="w100"
            placeholder="请输入厂商"
            :restaurants="factoryList"
            :state="formInline.factory"
            @handleSelect="handleSelectFactory">
          </AutoCompleteCustom>
        </el-form-item>
        <el-form-item label="">
          <el-input size="small" v-model="formInline.model" placeholder="输入型号" clearable></el-input>
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker
            clearable
            size="small"
            v-model="formInline.timer"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            :default-time="['00:00:00', '23:59:59']"
            value-format="timestamp">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-select size="small" v-model="formInline.orderStatus" placeholder="请选择订单状态" multiple>
            <el-option v-for="type in orderStatusList" :label="type.label" :value="type.value" :key="type.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        </el-form-item>
      </el-form>
      <!--列表-->
      <div class="relative">
        <table-top
          :refCustom="refCustom"
          :sheetLast="sheetLast"
          :formInline="formInline"
          :exportExcelInfo="exportExcelInfo"
          :exportExcelArry="exportExcelArry"
          :exportExcelHead="exportExcelHead"
          :multipleSelection="multipleSelection"
          :exportExcelRequest="exportExcelRequest"
          @onSuccess="onSuccess">
        </table-top>
        <div class="relative">
          <el-table
            :header-cell-style="{'font-weight': '600', 'color':'#333'}"
            size="small" :data="listData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;"
            show-summary :summary-method="getSummaries"
            ref="multipleTable" @selection-change="handleSelectionChange">
            <el-table-column align="center" sortable prop="factory" label="厂商" width="100px">
            </el-table-column>
            <el-table-column align="center" sortable prop="model" label="型号" width="100px">
            </el-table-column>
            <el-table-column align="center" sortable prop="orderAmount" label="订单数量" width="100px">
            </el-table-column>
            <el-table-column align="center" sortable prop="cutOrders" label="砍单数量" width="100px">
            </el-table-column>
            <el-table-column align="center" sortable prop="unpaidAmount" label="未交数量" width="120px">
            </el-table-column>
            <el-table-column align="center" label="操作" min-width="300">
              <template slot-scope="scope">
                <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button size="mini" type="danger" @click="deleteColumn(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页组件 -->
        <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
      </div>
    </div>

    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click="closeDialog">
      <el-form label-width="120px" :model="editForm" :rules="rules" ref="editForm">
        <el-form-item label="部门名称" prop="deptName">
          <el-input size="small" v-model="editForm.deptName" auto-complete="off" placeholder="请输入部门名称"></el-input>
        </el-form-item>
        <el-form-item label="部门代码" prop="deptNo">
          <el-input size="small" v-model="editForm.deptNo" auto-complete="off" placeholder="请输入部门代码"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deptList, deptSave, deptDelete } from '../../api/userMG'
import Pagination from '../../components/Pagination'
// 输入建议
import AutoCompleteCustom from "@/components/AutoCompleteCustom.vue"
import {mapGetters, mapState} from "vuex";
import TableTop from "@/components/table-top.vue"
export default {
  // 注册组件
  components: {
    Pagination,
    AutoCompleteCustom,
    TableTop
  },
  data() {
    return {
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      title: '添加',
      editForm: {
        deptId: '',
        deptName: '',
        deptNo: '',
      },
      // rules表单验证
      rules: {
        deptName: [
          { required: true, message: '请输入部门名称', trigger: 'blur' }
        ],
        deptNo: [{ required: true, message: '请输入部门代码', trigger: 'blur' }]
      },
      formInline: {
        page: 1,
        pagenum: 10,
        factory: '',
        orderStatus: 0,
        model: '',
        timer: '',
      },
      factoryList:[],
      orderStatusList: [
        {value: '全部',label: '全部'},
        {value: '已结案',label: '已结案'},
        {value: '未完结',label: '未完结'}
      ],
      listData: [], //用户数据
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      },
      // 导出start
      // 上传excel
      isShow: false,
      //导出表格字段及formatter信息
      exportExcelArry: [
        {
          prop: 'orderDate',
          label: '下单时间',
          formatterFlag: true,
          formatterType: 'time-type',
        },
        {
          prop: 'model',
          label: '型号',
          formatterFlag: false
        },
        {
          prop: 'header',
          label: '负责人',
          formatterFlag: false
        },
        {
          prop: 'orderAmount',
          label: '订单数量',
          formatterFlag: false
        },
        {
          prop: 'orderStatus',
          label: '订单状态',
          formatterFlag: false,
          // formatterFlag: true,
          // formatterType: 'common-type',
          // formatterInfo: [{value: 0,label: '下单'},{value: 1,label: '砍单'},{value: 2,label: '结案'}]
        },
        {
          prop: 'materialStatus',
          label: '物料状态',
          formatterFlag: false,
          // formatterFlag: true,
          // formatterType: 'common-type',
          // formatterInfo: [{value: 0,label: '进度正常'},{value: 1,label: '进度异常'},{value: 1,label: '已齐套'}]
        },
        {
          prop: 'unpaidAmount',
          label: '未交数量',
          formatterFlag: false
        },
        {
          prop: 'cutOrders',
          label: '砍单数量',
          formatterFlag: false
        },
        {
          prop: 'completeTime',
          label: '齐套时间',
          formatterFlag: true,
          formatterType: 'time-type',
        },
      ],
      // 导出excel表格宽高列表
      exportExcelHead:[
        { wpx: 120, wch: 20 },
        { wpx: 120, wch: 20 },
        { wpx: 120, wch: 20 },
        { wpx: 120, wch: 20 },
        { wpx: 120, wch: 20 },
        { wpx: 120, wch: 20 },
        { wpx: 120, wch: 20 },
        { wpx: 120, wch: 20 },
        { wpx: 140, wch: 20 },
      ],
      //导出excel表格id及excel名称
      exportExcelInfo: {
        excelId: 'index-order',
        excelName: '记录.xlsx'
      },
      //需要导出的table的选择数据
      multipleSelection: [],
      refCustom: 'myChild',
      // 表格列最后一列，有边框样式，手动去掉
      sheetLast: '',
      // 导出数据接口
      exportExcelRequest:'DeliveryProgress',
      formInlineExcel: {
        page: 1,
        pagenum: 10,
      },
      // 导出end

    }
  },
  /**
   * 数据发生改变
   */

  /**
   * 创建完毕
   */
  created() {
    this.defaultMultipleSelect();
    this.getData(this.formInline)
  },
  computed:{
    ...mapGetters(['userAuthList']),
    permissionObj(){
      if(this.userAuthList&&this.userAuthList.length>0){
        return this.authListFilter(this.userAuthList,'orderManagement', 'permissionObj')
      }
    }
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    //获取厂商+型号列表
    defaultMultipleSelect(){
      this.loading = true

      /***
       * 调用接口，注释上面模拟数据 取消下面注释
       */

      this.apiUrl.defaultMultipleSelect()
        .then(res => {
          this.loading = false
          const { code, data:{
            factoryList
          }, msg } = res;
          if (code != 0) {
            this.$message({
              type: 'info',
              message: msg
            })
          } else {
            // 厂商列表
            if(factoryList){
              this.factoryList = this.SelectMap(factoryList);
            }
          }
        })
        .catch(err => {
          if(err&&err.isCancel) return
          this.loading = false
          this.$message.error('列表加载失败，请稍后再试！')
        })
    },
    // 获取交货进度列表
    getData(parameter) {
      this.loading = true

      /***
       * 调用接口，注释上面模拟数据 取消下面注释
       */
      this.apiUrl[this.exportExcelRequest](this.editForm,"GET")
        .then(res => {
          this.loading = false
          const { code, data:{list,totalnum}, msg } = res;
          if (code != 0) {
            this.$message({
              type: 'info',
              message: msg
            })
          } else {
            this.listData = list
            // 分页赋值
            this.pageparm.currentPage = this.formInline.page
            this.pageparm.pageSize = this.formInline.pagenum
            this.pageparm.total = totalnum
          }
        })
        .catch(err => {
          if(err&&err.isCancel) return
          this.loading = false
          this.$message.error('交货进度列表加载失败，请稍后再试！')
        })
    },
    // 分页插件事件
    callFather(parm) {
      const vm = this
      vm.formInline = {
        ...vm.formInline,
        page: parm.currentPage,
        pagenum: parm.pageSize
      }
      vm.getData(vm.formInline)
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        // if(column.property  != 'orderAmount' && column.property != 'cutOrders') return;
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index];
        } else {
          sums[index] = '';
        }
      });

      return sums;
    },
    // 搜索事件
    search() {
      const vm = this
      vm.formInline = {
        ...vm.formInline,
        page: 1
      }
      vm.getData(vm.formInline)
    },
    //显示编辑界面
    handleEdit: function(index, row) {
      this.editFormVisible = true
      if (row != undefined && row != 'undefined') {
        this.title = '修改'
        this.editForm.deptId = row.deptId
        this.editForm.deptName = row.deptName
        this.editForm.deptNo = row.deptNo
      } else {
        this.title = '添加'
        this.editForm.deptId = ''
        this.editForm.deptName = ''
        this.editForm.deptNo = ''
      }
    },
    // 编辑、增加页面保存方法
    submitForm(editData) {
      this.$refs[editData].validate(valid => {
        if (valid) {
          this.apiUrl.GetHeaderList(this.editForm,"GET")
            .then(res => {
              this.editFormVisible = false
              this.loading = false
              const { code, msg } = res
              if (code != 0) {
                this.getData(this.formInline)
                this.$message({
                  type: 'success',
                  message: '保存成功！'
                })
              } else {
                this.$message({
                  type: 'info',
                  message: msg
                })
              }
            })
            .catch(err => {
              if(err&&err.isCancel) return
              this.editFormVisible = false
              this.loading = false
              this.$message.error('保存失败，请稍后再试！')
            })
        } else {
          return false
        }
      })
    },
    // 删除
    deleteColumn(index, row) {
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.apiUrl.GetHeaderList(row.deptId,"GET")
            .then(res => {
              const { code, msg } = res;
              if (code == 0) {
                this.$message({
                  type: 'success',
                  message: '已删除!'
                })
                this.getData(this.formInline)
              } else {
                this.$message({
                  type: 'info',
                  message: msg
                })
              }
            })
            .catch(err => {
              if(err&&err.isCancel) return
              this.loading = false
              this.$message.error('删除失败，请稍后再试！')
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false
    },
    handleSelectFactory(item) {
      this.formInline.factory = item.value
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 上传excel成功
    async onSuccess(data) {
      console.log(data);
      // 数据库的key为英文，我们上传的key为中文，需要一一转化
      const userRelations = Object.fromEntries(this.exportExcelArry.map((item)=>{
        return [item.label,item.prop]
      }))
      // 将key值一一对应
      const newArr = data.results.map((item) => {
        let userInfo = {};
        Object.keys(item).forEach((key) => {
          if(userRelations[key]){
            userInfo[userRelations[key]] = item[key];
          }
          // userInfo[userRelations[key]] = item[key];
        });
        return userInfo;
      });

      // const newArr = data.results

      console.log(newArr);
      const param = {
        excelFrom: 'BillingPlan',
        excelList: newArr,
      }
      //   await importEmployee(param); // 调用上传接口
      this.$message("上传文件成功");
      this.isShow = false;
    },

  }
}
</script>

<style lang="less" scoped>

</style>

